<?php
include_once 'application/application.php';

class Page_users {

    private $u_table        = 'users_list';
    private $ugroups_table  = 'users_group_list';
    private $uwlink_table   = 'users_views_link';

    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }

    
    
    
    
    
    public function checkFields($params) {
        $wrongFields = array();

        /*
        $name = 'firstname';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'lastname';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;
        
        */
        
        $name = 'organisation';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'job_position';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'phone';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        $name = 'email';
        $var = $params[$name];
        $msg = '';
        if (!$msg && !$var) $msg = 'Не заполнено обязательное поле';
        if ($msg) $wrongFields[$name] = $msg;

        return $wrongFields;
    }

    
    
    
    
    
    
    

    public function getUsersList() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        
        $allGroups = getAllUserGroups();
        $allUsers = getAllUsers();
        
        
        $data = array();
        foreach ($allGroups as $key=>$gr) {
            $data[$key] = $gr;
            $data[$key]['users'] = array();
        }
        
        foreach ($allUsers as $key=>$u) {
            $gr = Arr::getValue($u, 'filter_id', 0);
            if (!array_key_exists($gr, $data)) continue;
            
            $data[$gr]['users'][$key] = fetchUser($u);
        }
        
        $J->data = $data;
        return $J;
    }
    
    
    
    public function getUserAccessInfo() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $ids = $J->readVar('users');
        
        if (!$ids) return $J->error ('No user selected');
        if (!is_array($ids)) $ids = array($ids);
        
        $usersData = array();
        $accessData = array();
        $allUsers = getAllUsers();
        $allViews = selectViewableObjectsFromSet(getAllViews());
        
        ConceptionsCollection::Init();
        foreach($allViews as $v) {
            $dv = array(
                'id'        => $v['id'],
                'obj_name'  => $v['obj_name'],
                'conception'=> $v['conception']
            );
            
            ConceptionsCollection::storeObject($dv);
        }
        
        foreach ($ids as $id) {
            $id = (int)$id; 
            if (!$id) continue;
            $u = Arr::getValue($allUsers, $id, false);
            if (!$u || !is_array($u)) continue;
            
            $res = DB::query("SELECT obj_id FROM $this->uwlink_table WHERE user_id = $id");
            if (!DB::$lastReqState) $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
            
            $accessData[$id] = array();
            while ($row = $res->fetch_assoc()) {
                $objid = Arr::getValue($row, 'obj_id', FALSE);
                if ($objid) $accessData[$id][$objid] = 1;
            }

            $u = fetchUser($u);
            $usersData[$id] = $u;
            
        }
        
        $J->usersData = $usersData;
        $J->accessData = $accessData;
        $J->viewsData = ConceptionsCollection::allSorted();
        return $J;
    }
    
    
    
    public function manageObject() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $action = $J->readVar('action');
        $user = (int)$J->readVar('user');
        $object = (int)$J->readVar('object');
        
        
        $allUsers = getAllUsers();
        $allViews = getAllViews();
        
        if (!array_key_exists($user, $allUsers)) return $J->error('Пользователь не найден');
        if (!array_key_exists($object, $allViews)) return $J->error('Отображение не найдено');
        
        switch($action){
            case ACTIONS::USERS_DENY_ACCESS:

                $res = DB::query("DELETE FROM $this->uwlink_table WHERE obj_id='$object' AND user_id='$user'");
                if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');

                $res = DB::query("SELECT * FROM $this->uwlink_table WHERE obj_id='$object' AND user_id='{$user}'");
                if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
                $J->state = (DB::$mysqli->affected_rows < 1);
                return $J;



            case ACTIONS::USERS_ALLOW_ACCESS:
                $res = DB::query("SELECT * FROM $this->uwlink_table WHERE obj_id='$object' AND user_id='{$user}'");
                if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
                
                if(DB::$mysqli->affected_rows) {
                    $J->state = 1;
                    return $J;
                }

                $res = DB::query("INSERT INTO $this->uwlink_table SET obj_id='$object', user_id='{$user}'");
                $J->state = (DB::$lastReqState && DB::$mysqli->affected_rows);
                return $J;

        }
        
        return $J->error("Неизвестный запрос ($action)");
    }
    
    
    public function manageCnc() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $user =         (int)$J->readVar('user');
        $conception =   (int)$J->readVar('conception');
        $setaccess =    $J->readVar('setaccess')? true:false;
        
        
        $allUsers = getAllUsers();
        $allViews = getAllViews();
        
        if (!array_key_exists($user, $allUsers)) return $J->error('Пользователь не найден');
        
        
        ConceptionsCollection::Init();
        foreach($allViews as $v) {
            $dv = array(
                'id'        => $v['id'],
                'obj_name'  => $v['obj_name'],
                'conception'=> $v['conception']
            );
            
            ConceptionsCollection::storeObject($dv);
        }
        
        $cnc = ConceptionsCollection::getConceptionById($conception);
        if (!$cnc || !($cnc instanceof RPConception)) return $J->error('Концепция не найдена');
        
        $views = array();
        if ($cnc->hasChild()) {
            foreach ($cnc->children as $cc) {
                if (is_array($cc->objects)) foreach ($cc->objects as $o) $views[] = Arr::getValue ($cc->objects, 'id', 0);
            } 
        }
        if (is_array($cnc->objects)) foreach ($cnc->objects as $o) {
            $views[] = Arr::getValue ($o, 'id', 0);
        }
        $text_ids = join(',', $views);
        if ($text_ids) {
            $res = DB::query("DELETE FROM $this->uwlink_table WHERE obj_id IN ($text_ids) AND user_id='$user'");
            if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');

            if ($setaccess) {
                $varr = array();
                $q = "INSERT INTO `$this->uwlink_table` (`id`, `user_id`, `obj_id`) VALUES ";
                foreach ($views as $v) $varr[] = "(NULL, '{$user}', '{$v}' )"; 
                $q .= join(', ', $varr);

                $res = DB::query($q);
                if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
            }
        }
            
        
        
        $J->state = 1;
        return $J;
    }
    
    
    
    public function deactivateUser() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $user = (int)$J->readVar('user');

        $allUsers = getAllUsers();
        if (!array_key_exists($user, $allUsers)) return $J->error('Пользователь не найден');
        
        $res = DB::query("UPDATE users_list SET rang='0' WHERE id = $user");
        if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
        
        if (class_exists('Log')) Log::Save(OPERATION::DEACTIVATE_USER, array('id'=>$user));
        $J->state = 1;
        return $J;
    }
    
    
    public function activateUser() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $user = (int)$J->readVar('user');

        $allUsers = getAllUsers();
        if (!array_key_exists($user, $allUsers)) return $J->error('Пользователь не найден');

        $res = DB::query("UPDATE users_list SET rang='1' WHERE id = $user");
        if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
        
        if (class_exists('Log')) Log::Save(OPERATION::ACTIVATE_USER, array('id'=>$user));
        $J->state = 1;
        return $J;
    }
    
    public function deleteUser() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $user = (int)$J->readVar('user');

        $allUsers = getAllUsers();
        if (!array_key_exists($user, $allUsers)) return $J->error('Пользователь не найден');
        
        $res = DB::query("UPDATE users_list SET deleted='1' WHERE id = $user");
        if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
        
        if (class_exists('Log')) Log::Save(OPERATION::DELETE_USER, array('id'=>$user));
        
        $J->state = 1;
        return $J;
    }
    
    
    
    public function updateUser() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        
        
        $params = array();
        $params['action']        = $J->readVar('action');
        $params['id']            = (int)$J->readVar('f_user_id');
        $params['organisation']  = mysql_escape_string($J->readVar('f_user_organisation'));
        $params['job_position']  = mysql_escape_string($J->readVar('f_user_job_position'));
        $params['email']         = mysql_escape_string($J->readVar('f_user_email'));
        $params['phone']         = mysql_escape_string($J->readVar('f_user_phone'));
        $params['newpassword']   = mysql_escape_string($J->readVar('f_user_newpassword'));
        // не редактируются
        
        $params['first_name']    = mysql_escape_string($J->readVar('f_user_first_name'));
        $params['last_name']     = mysql_escape_string($J->readVar('f_user_last_name'));
        $params['login']         = mysql_escape_string($J->readVar('f_user_login'));

        if (!$params['id']) return $J->error('Ошибочный запрос: не указан пользователь');
        
        $wrongFields = $this->checkFields($params);
        if (count($wrongFields)) {
            $J->wrongFields = $wrongFields;
            return $J;
        }
        
        $res = DB::query("SELECT * FROM users_list WHERE deleted=0 AND id = {$params['id']}");
        if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
        $oldval = $res->fetch_assoc();
        if (!is_array($oldval)) return $J->error('Пользователь не существует или помечен удалённым');
        
        $setparams = array('organisation','job_position','email','phone');
        $set = array();
        foreach ($setparams as $field) {
            $set[$field] = "$field='{$params[$field]}'";
        }
        
        /*
        $set['organisation'] = "organisation='{$params['f_user_organisation']}'";
        $set['job_position'] = "job_position='{$params['f_user_job_position']}'";
        $set['email'] = "email='{$params['f_user_email']}'";
        $set['phone'] = "phone='{$params['f_user_phone']}'";
        
        $set['first_name'] = $params['f_user_first_name'];
        $set['last_name'] = $params['f_user_last_name'];
        $set['login'] = $params['f_user_login'];
        */
        
        if ($params['newpassword']) {
            $hashsalt = generatePasswordSalt($params['newpassword']);
            unset($params['newpassword']);
            $set['password'] = "password='".Arr::getValue($hashsalt, 'password', '')."'";
            $set['salt'] = "salt='".Arr::getValue($hashsalt, 'salt', '')."'";
        }
        
        $set_string = join(', ', $set);
        $sql = "UPDATE users_list SET $set_string WHERE id = {$params['id']}";
        $res = DB::query($sql);
        if (!DB::$lastReqState) return $J->error('Ошибка при выполнении запроса <!--('.DB::$mysqli->error.')-->');
        
        if (class_exists('Log')) Log::Save(OPERATION::UPDATE_USER, array('id'=>$params['id'], 'old_val'=>$oldval, 'new_val'=>$params));
        $J->state = 1;
        $J->insertedId = $params['id'];
        
        foreach ($setparams as $field) {
            $oldval[$field] = $params[$field];
        }
        $J->user = fetchUser($oldval);
        
        return $J;
    }
    
    
    public function loadPhoto() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $id = (int)$J->readVar('id');
        
        $JL = UserAvatar::loadAva($id, 'user_image');
        
        if ($JL->getState()) $J->ava = $JL->ava;
        else $J->error ($JL->getErrorString ());
        
        return $J;
        
    }
    
    public function deletePhoto() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        
        $J->readVar('action');
        $id = (int)$J->readVar('id');
        
        $JL = UserAvatar::deleteAva($id);
        
        if ($JL->getState()) $J->ava = $JL->ava;
        else $J->error ($JL->getErrorString ());
        
        return $J;
    }
    
    
    public function moveUser() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        $J->readVar('action');
        $users = join(',', $J->readVar('users'));
        $group = (int) $J->readVar('groupId');
        $q = "UPDATE `users_list` SET `filter_id`=$group WHERE id IN ($users)";
        if (!$res = DB::query($q)) return $J->error(DB::$mysqli->error);
        $J->state = 1;
        return $J;
    }

    public function createGroup() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        $J->readVar('action');
        $users = join(',', $J->readVar('users'));
        $group = $J->readVar('groupName');
        DB::query("BEGIN");
            if (!DB::query("INSERT INTO `users_group_list` (`filter_name`) VALUES ('$group')"))
                return $J->error(DB::$mysqli->error);
            DB::query("SET @groupID := LAST_INSERT_ID()");
            if (!$res = DB::query("UPDATE `users_list` SET `filter_id`=@groupID WHERE id IN ($users)"))
                return $J->error(DB::$mysqli->error);
        if (!DB::query("COMMIT")) return $J->error(DB::$mysqli->error);
        $J->state = 1;
        return $J;
    }

    public function renameGroup() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        $J->readVar('action');
        $id = $J->readVar('groupId');
        $group = $J->readVar('groupName');
        if (!DB::query("UPDATE `users_group_list` SET `filter_name`='$group' WHERE id IN ($id)"))
            return $J->error(DB::$mysqli->error);
        $J->state = 1;
        return $J;
    }

    public function deleteGroup() {
        $J = new JSON();
        if (!Auth::isLogged()) return $J->error('not_logged');
        $J->readVar('action');
        $group = (int) $J->readVar('groupId');
        if ($group == 1) return $J->error('Таблицу с id 1 удалить нельзя');
        $q = sprintf(
            "SET @group = %d;
            BEGIN;

                UPDATE `users_list`
                    SET `filter_id` = 1
                    WHERE `filter_id` = @group;

                DELETE
                    FROM `users_group_list`
                    WHERE `id`= @group LIMIT 1;

            COMMIT", $group
        );

        $q = explode(';', $q); $q = array_map('trim', $q);
        foreach($q as &$query) {
            if (!$res = DB::query($query)) return $J->error(DB::getError());
        }
        $J->state = 1;
        return $J;
    }

    public function outPageAccess() {
        $params = array();

        $this->printOut(includeFile(APP_PAGE_PARTS.'users_page_access.php', $params));
    }

    public function outPageGroups() {
        $params = array();

        $this->printOut(
             includeFile(APP_PAGE_PARTS.'users_page_access.php', $params)
            .includeFile(APP_PAGE_PARTS.'forms/form_user_add_group.php', $params)
        );
    }

    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }

}

$page = new Page_users();
if ($page->action) {
    if ($page->action == ACTIONS::USERS_FULL_LIST)          echo $page->getUsersList();
    if ($page->action == ACTIONS::USERS_GET_ACCESS_INFO)    echo $page->getUserAccessInfo();
    if ($page->action == ACTIONS::USERS_ALLOW_ACCESS)       echo $page->manageObject();
    if ($page->action == ACTIONS::USERS_DENY_ACCESS)        echo $page->manageObject();
    if ($page->action == ACTIONS::USERS_SET_CNC_ACCESS)     echo $page->manageCnc();
    if ($page->action == ACTIONS::USERS_DEACTIVATE_USER)    echo $page->deactivateUser();
    if ($page->action == ACTIONS::USERS_ACTIVATE_USER)      echo $page->activateUser();
    if ($page->action == ACTIONS::USERS_DELETE_USER)        echo $page->deleteUser();
    if ($page->action == ACTIONS::USERS_UPDATE_USER)        echo $page->updateUser();
    if ($page->action == ACTIONS::USERS_LOAD_PHOTO)         echo $page->loadPhoto();
    if ($page->action == ACTIONS::USERS_DELETE_PHOTO)       echo $page->deletePhoto();

    if ($page->action == ACTIONS::USERS_CREATE_GROUP)       echo $page->createGroup();
    if ($page->action == ACTIONS::USERS_MOVE_USER)          echo $page->moveUser();
    if ($page->action == ACTIONS::USERS_RENAME_GROUP)       echo $page->renameGroup();
    if ($page->action == ACTIONS::USERS_DELETE_GROUP)       echo $page->deleteGroup();
}
else  {
    Navbar::$expanded = 'lm-manage-usr';
    if (array_key_exists('access', $_REQUEST)) {
        if (!Auth::isLogged()) reLocate ('index.php');
        Navbar::$active = 'usr-access';
        $page->outPageAccess();
    } elseif (array_key_exists('groups', $_REQUEST)) {
        if (!Auth::isLogged()) reLocate ('index.php');  
        Navbar::$active = 'usr-groups';
        $page->outPageGroups();
    }
}
?>
